package com.zz.bid.service;

import com.zz.bid.exception.base.BidException;
import com.zz.bid.mapper.SettleFlowMapper;
import com.zz.bid.pojo.entity.SettleFlowEnum;
import com.zz.bid.pojo.to.SettleFlowDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class SettleFlowService {
    @Autowired
    SettleFlowMapper flowMapper;

    public void addFlows(int bidId, String userName) throws BidException {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (SettleFlowEnum flowEnum : SettleFlowEnum.values()) {
                SettleFlowDetails settleFlowDetails = new SettleFlowDetails();
                settleFlowDetails.setSettleId(bidId);
                settleFlowDetails.setFlowId(flowEnum.getId());
                settleFlowDetails.setLastUpdateTime(sdf.format(new Date()));
                settleFlowDetails.setLastUpdateUser(userName);
                settleFlowDetails.setApproved(false);
                flowMapper.insert(settleFlowDetails);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BidException(e.getMessage());
        }
    }

    public List<SettleFlowDetails> getByBidId(int settleId) throws BidException {
        try {
            return flowMapper.getSettleFlows(settleId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BidException(e.getMessage());
        }
    }

    public void updateFlow(SettleFlowDetails settleFlowDetails) throws BidException {
        try {
            flowMapper.update(settleFlowDetails);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BidException(e.getMessage());
        }
    }

    public void approved(Integer bidId, Integer flowId, String user) throws BidException {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SettleFlowDetails settleFlowDetails = flowMapper.getSettleFlow(bidId, flowId);
            settleFlowDetails.setApproved(!settleFlowDetails.isApproved());
            settleFlowDetails.setLastUpdateUser(user);
            settleFlowDetails.setLastUpdateTime(sdf.format(new Date()));
            flowMapper.update(settleFlowDetails);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BidException(e.getMessage());
        }
    }
}
